package de.fhkl.android.activities;

import java.util.ArrayList;
import de.fhkl.android.R;
import de.fhkl.android.R.array;
import de.fhkl.android.R.drawable;
import de.fhkl.android.R.raw;
import de.fhkl.android.services.MainService;
import de.fhkl.android.utils.AndroidUtil;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.Prediction;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.TableLayout.LayoutParams;

public class MainActivity extends Activity {

	/** initiate when the activity is first created. */
	private String[] moduleNames;
	private int moduleCount, moduleCountPerColumn = 3;

	/** Size of StatusBar and Workspace ,in dip */
	private int statusBarHeight = 25;
	private int workspaceWidth = 320;
	private int workspaceHeight = 480 - statusBarHeight;
	private int gridViewSpacing = 5;
	private int gridViewPaddingLeft = 5, gridViewPaddingRight = 5,
			gridViewPaddingTop = 5, gridViewPaddingBottom = 5;
	private int buttonWidth = 100, buttonHeight = 100;

	private int gridViewBgColor = Color.BLACK;
	private View mainView;

	private GestureLibrary gestureLib;

	// the current showing page number(0 - n).
	private float x, xRaw;
	private String tag = "MainActivity";

	public void onCreate(Bundle savedInstanceState) {
		Log.i(tag, "begin");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		gestureLib = GestureLibraries
				.fromRawResource(this, R.raw.gestures_main);
		// gestureLib = GestureLibraries.fromFile("/sdcard/gestures");
		if (!gestureLib.load()) {
			Toast.makeText(this, "Could not load /sdcard/gestures",
					Toast.LENGTH_SHORT).show();
			finish();
		}
		moduleNames = getResources().getStringArray(R.array.module_name);
		moduleCount = moduleNames.length;
		mainView = initViews();
		setContentView(mainView);
		
		if (!serviceIsRunning()){
			this.startService(new Intent(this,MainService.class));
		}
		

	}

	private View initViews() {

		DisplayMetrics dm = getResources().getDisplayMetrics();
		workspaceWidth = dm.widthPixels;
		workspaceHeight = dm.heightPixels - statusBarHeight;
		Log.e(tag, "colCountInShortEdge=" + moduleCountPerColumn);
		Log.e(tag, "workspaceWidth" + workspaceWidth);
		Log.e(tag, "workspaceHeight" + workspaceHeight);

		ArrayList<Button> buttonList = new ArrayList<Button>();
		for (int i = 0; i < moduleCount; i++) {
			Button button = buttonFactory(moduleNames[i]);
			buttonList.add(button);
		}

		GestureOverlayView gestureView = new GestureOverlayView(this);
		gestureView.setFadeOffset(100);
		gestureView.setGestureVisible(true);
		gestureView.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.FILL_PARENT));
		gestureView
				.addOnGesturePerformedListener(new OnGesturePerformedListener() {
					public void onGesturePerformed(GestureOverlayView view,
							Gesture gesture) {

						ArrayList<Prediction> predictions = gestureLib
								.recognize(gesture);
						Log.i("gestureView",
								"onGesturePerformed" + predictions.size());
						if (predictions.size() > 0) {
							Prediction prediction = (Prediction) predictions
									.get(0);
							Log.i("score", prediction.score + "");
							if (prediction.score > 5) {
								if (prediction.name.equals("left")) {
									
								} else if (prediction.name.equals("right")) {
									
								}

							}
						}
					}
				});

		GridView gridView = new GridView(this);
		gridView.setPadding(gridViewPaddingLeft, gridViewPaddingTop,
				gridViewPaddingRight, gridViewPaddingBottom);
		gridView.setBackgroundColor(gridViewBgColor);
		gridView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
		gridView.setNumColumns(moduleCountPerColumn);
		gridView.setHorizontalSpacing(gridViewSpacing);
		gridView.setVerticalSpacing(gridViewSpacing);
		gridView.setAdapter(new ButtonAdapter(buttonList));
		
		gestureView.addView(gridView);
		return gestureView;

	}
	
	private boolean serviceIsRunning()
	 {
	  ActivityManager myManager=(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
	  ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(30);
	  for(int i = 0 ; i<runningService.size();i++)
	  {
	   if(runningService.get(i).service.getClassName().toString().equals("de.fhkl.services.MainService"))
	   {
		Log.w(tag,"Service is running!");
	    return true;
	   }
	  }
	  Log.w(tag,"Service is stopped!");
	  return false;
	 }

	private Button buttonFactory(String name) {

		final Intent intent = new Intent();
		Button button = new Button(this);
		button.setOnTouchListener(new Button.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				Log.i("buttonTouch", "action = " + event.getAction());
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					xRaw = event.getX();
				}
				if (event.getAction() == MotionEvent.ACTION_UP) {
					x = event.getX();

					if (x - xRaw > 50) {
						// portraitLayout.showNext();
						// landscapeLayout.showNext();
						Log.i("flipper", "showNext()");
					} else if (xRaw - x > 50) {
						// portraitLayout.showPrevious();
						// landscapeLayout.showPrevious();
						Log.i("flipper", "showPrevious()");
					} else {
						startActivity(intent);
					}

				}
				return true;
			}
		});
		int bgId = 0;
		if (name.equals("cafeteria")) {
			intent.setClass(this, CafeteriaActivity.class);
			bgId = R.drawable.cafeteria;
		} else if (name.equals("library")) {
			intent.setClass(this, LibraryActivity.class);
			bgId = R.drawable.library;
		} else if (name.equals("schedule")) {
			intent.setClass(this, ScheduleActivity.class);
			bgId = R.drawable.schedule;
		} else if (name.equals("weather")) {
			intent.setClass(this, WeatherActivity.class);
			bgId = R.drawable.weather;
		} else if (name.equals("search")) {
			intent.setClass(this, SearchActivity.class);
			bgId = R.drawable.search;
		} else if (name.equals("pinwall")) {
			intent.setClass(this, PinwallActivity.class);
			bgId = R.drawable.pinwall;
		} else if (name.equals("campus")) {
			intent.setClass(this, CampusActivity.class);
			bgId = R.drawable.campus;
		} else if (name.equals("setting")) {
			intent.setClass(this, SettingActivity.class);
			bgId = R.drawable.setting;
		} else if (name.equals("room")) {
			intent.setClass(this, RoomActivity.class);
			bgId = R.drawable.room;
		} else {

		}
		
		int bWidth = AndroidUtil.dip2Px(this, buttonWidth);
		int bHeight = AndroidUtil.dip2Px(this, buttonHeight);
		button.setWidth(bWidth);
		button.setHeight(bHeight);
		Bitmap bMap = BitmapFactory.decodeResource(getResources(), bgId);
		Drawable drawable = new BitmapDrawable(Bitmap.createScaledBitmap(bMap,
				bWidth, bHeight, true));

		button.setBackgroundDrawable(drawable);

		return button;

	}

	protected void onNewIntent(Intent intent) {
		Log.e(tag, "new intent");
	}

	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		initViews();
	}

	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		Log.w(tag, "onSaveInstanceState");
	}

	public void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		Log.w(tag, "onRestoreInstanceState");
	}

}

class ButtonAdapter extends BaseAdapter {
	private ArrayList<Button> buttonList;
	public int page;

	public ButtonAdapter(ArrayList<Button> buttonList) {
		this.buttonList = buttonList;
	}

	public int getCount() {
		if (buttonList == null) {
			return -1;
		} else {
			return buttonList.size();
		}
	}

	public Object getItem(int position) {
		if (buttonList == null) {
			return null;
		} else {
			return buttonList.get(position);
		}
	}

	public long getItemId(int position) {
		if (buttonList == null) {
			return -1;
		} else {
			return buttonList.get(position).getId();
		}

	}

	public View getView(int position, View convertView, ViewGroup parent) {
		return buttonList.get(position);
	}

}